package com.example.sbsj.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.sbsj.sys.entity.User;
import com.example.sbsj.sys.service.IUserService;
import com.example.sbsj.utils.JWTUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lijunjie
 * @since 2019-12-13
 */
@RestController
@RequestMapping("/sys/user")
public class UserController {

    @Resource
    private IUserService userService;

    @PostMapping("/login")
    public String login(User user){

        //获得用户主体
        Subject subject = SecurityUtils.getSubject();
        //用户名密码登录token
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        subject.login(token);

        //根据username获取user
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",user.getUsername());
        User u = userService.getOne(queryWrapper);
        //登录成功后生成token,返回到前端
        String jwtToken = JWTUtil.sign(u.getId(),u.getPassword());

        return jwtToken;
    }

    @GetMapping("query")
    @RequiresPermissions("sys:user:query")
    public String query(){
        return "qurey";
    }
}

